const { route } = require("../decorator/router")
const multer = require('koa-multer');//加载koa-multer模块 
const path = require('path')
var qiniu = require('qiniu');
var fs = require('fs-extra');
let filename = ''
let filenames = ''
let userName= ''
let paths = path.join(__dirname, '/image')
const { User } = require('../dataDB/user')

var storage = multer.diskStorage({
    //文件保存路径  
    destination: function (req, file, cb) {
        cb(null, paths)
    },
    //修改文件名称  
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        userName = fileFormat[0]
        filename = fileFormat.slice(0,fileFormat.length-1).join('.') + "." + fileFormat[fileFormat.length - 1]
        cb(null, filename);
    }
})

var upload = multer({ storage: storage });
route.post('/update', upload.single('file'), async (ctx, next) => {
    try {
        console.log(ctx.request.body)
        console.log(filename)
        var accessKey = '*************dfRGsej-5NdXi*************'
        var secretKey = '*************nqYsmYIQUC*************'
        var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var config = new qiniu.conf.Config();
    
        var options = {
            scope: 'lxlong'
        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken = putPolicy.uploadToken(mac);
        // 空间对应的机房
        config.zone = qiniu.zone.Zone_z2
        var localFile = path.join(paths + '/' + filename)
        console.log('路劲', localFile)
        var formUploader = new qiniu.form_up.FormUploader(config);
        var putExtra = new qiniu.form_up.PutExtra(); 
        var key = filename
        // 文件上传
        let data = await new Promise((resolve, reject) => {
            formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr,
                respBody, respInfo) {
                if (respErr) {
                    throw respErr;
                    console.log('上传错误', respErr)
                    reject(respErr)
                    return
                }
                if (respInfo.statusCode == 200) {
                    resolve({
                        success: true,
                        message: '上传成功',
                        respBody
                    })
                    fs.remove(localFile, function (err) {
                        if (err) {
                            console.error('错误', err)
                            return
                        }
                    })
                } else {
                    console.log(respInfo.statusCode);
                    console.log(respBody);
                    reject({respBody})
                }
            });
        })
        if (data.success) {
            let url = `http://p612demvl.bkt.clouddn.com/${data.respBody.key}`
            let dataUrl = await User.update({userName}, {$set:{Headimagelink:url}})
            if (dataUrl.ok === 1) {
                ctx.body = {
                    result: 1,
                    message: dataUrl,
                    success: true
                }
            }
        }
    } catch (e) {
        console.log(e)
        ctx.body = {
            result: 0,
            success: false,
            message: e
        }
    }
})